package protocol.transactions;

import java.util.List;

import protocol.XoneProtocol;
import protocol.XoneService;
import protocol.XoneServiceCode;
import protocol.meta.BaseData;

import com.google.gson.Gson;
import com.netease.http.THttpRequest;
import com.netease.http.cache.HttpCache;
import com.netease.http.cache.HttpCacheManager;
import com.netease.task.AsyncTransaction;
import com.netease.task.NotifyTransaction;
import com.netease.task.TransTypeCode;
import com.netease.task.example.StringAsyncTransaction;

import db.manager.ManagerAccount;
import db.manager.ManagerAccount.Account;

public abstract class XoneBaseTransaction extends StringAsyncTransaction {
    private Object mRequest;
    /**标志该协议请求是否需要登录过才能执行，是的话在有未完成登录前需要加入等待执行队列*/
    private boolean mNeedLogin = false;
    private XoneBaseTransaction mCurrentTx;

    public XoneBaseTransaction(int type) {
        super(type);
        mCurrentTx = this;
    }
    public void setNeedLogin(boolean needlogin){
        if(mNeedLogin != needlogin){
            mNeedLogin = needlogin;
        }
    }
    public boolean isNeedLogin(){
        return mNeedLogin;
    }
    private static final int TRANSACTION_TYPE_ECHO_BASE = 0x100;
    /**
     * 获取ID和密钥
     */
    public static final int TRANSACTION_TYPE_GETIDKEY = TRANSACTION_TYPE_ECHO_BASE + 1;
    /**
     * 登录
     */
    public static final int TRANSACTION_TYPE_LOGIN = TRANSACTION_TYPE_ECHO_BASE + 2;
    /**
     * 检查手机号唯一性
     */
    public static final int TRANSACTION_TYPE_CHECK_PHONENUMBER = TRANSACTION_TYPE_ECHO_BASE +3;
    /**
     * urs登录的用户当昵称有重复时的重新注册
     */
    public static final int TRANSACTION_TYPE_URS_USER_REG = TRANSACTION_TYPE_ECHO_BASE + 4;
    /**
     * 第三方用户注册
     */
    public static final int TRANSACTION_TYPE_EXTERNAL_USER_REG = TRANSACTION_TYPE_ECHO_BASE + 5;
    /**
     * 获取手机验证码
     */
    public static final int TRANSACTION_TYPE_GET_CELLPHONE_CAPTCHA = TRANSACTION_TYPE_ECHO_BASE + 6;
    /**
     * 手机注册
     */
    public static final int TRANSACTION_TYPE_CELLPHONE_REG = TRANSACTION_TYPE_ECHO_BASE + 7;
    /**
     * 修改手机登录密码
     */
    public static final int TRANSACTION_TYPE_MODIFY_CELLPHONE_PW = TRANSACTION_TYPE_ECHO_BASE + 8;
    /**
     * 注销帐号
     */
    public static final int TRANSACTION_TYPE_LOGOUT = TRANSACTION_TYPE_ECHO_BASE + 9;
    /**
     * 同步社交帐号
     */
    public static final int TRANSACTION_TYPE_SYNC_BIND_ACCOUNT = TRANSACTION_TYPE_ECHO_BASE + 10;
    /**
     * 上传反馈日志
     */
    public static final int TRANSACTION_TYPE_POSTLOG = TRANSACTION_TYPE_ECHO_BASE + 11;
    /**
     * 发送反馈
     */
    public static final int TRANSACTION_TYPE_FEEDBACK = TRANSACTION_TYPE_ECHO_BASE + 12;
    /**
     *  获取应用参数
     */
    public static final int TRANSACTION_TYPE_GET_APP_SETTING = TRANSACTION_TYPE_ECHO_BASE + 13;
    /**
     *  设置应用参数
     */
    public static final int TRANSACTION_TYPE_SET_APP_SETTING = TRANSACTION_TYPE_ECHO_BASE + 14;
    /**
     * 获取推荐APP
     */
    public static final int TRANSACTION_TYPE_GET_RECOMM_APP = TRANSACTION_TYPE_ECHO_BASE + 15;
    /**
     * 检查版本信息
     */
    public static final int TRANSACTION_TYPE_CHECK_VERSION = TRANSACTION_TYPE_ECHO_BASE + 16;


    private static final int TRANSACTION_TYPE_JABBER_BASE = 0x10000;

    /**
     * 获取头条
     */
    public static final int TRANSACTION_TYPE_HEAD_RECOMMEND = TRANSACTION_TYPE_JABBER_BASE;

    /**
     * 获取输入提示关注用户列表
     */
    public static final int TRANSACTION_TYPE_USERINPUTTIPLIST = TRANSACTION_TYPE_JABBER_BASE + 1;
    /**
     * 获取输入提示订阅资讯源列表
     */
    public static final int TRANSACTION_TYPE_SOURCEINPUTTIPLIST = TRANSACTION_TYPE_JABBER_BASE + 2;
    /**
     * 获取输入提示热门话题列表
     */
    public static final int TRANSACTION_TYPE_TOPICINPUTTIPLIST = TRANSACTION_TYPE_JABBER_BASE + 3;
    /**
     * 获取输入提示订阅主题列表
     */
    public static final int TRANSACTION_TYPE_SUBJECTINPUTTIPLIST = TRANSACTION_TYPE_JABBER_BASE + 4;
    /**
     * 图片，视频，音频上传
     */
    public static final int TRANSACTION_TYPE_UPLOAD = TRANSACTION_TYPE_JABBER_BASE + 5;
    /**
     * 发表讨论
     */
    public static final int TRANSACTION_TYPE_POSTDISCUSS = TRANSACTION_TYPE_JABBER_BASE + 6;

    /**
     * 获取未读资讯条数
     */
    public static final int TRANSACTION_TYPE_GETUNREADINFOCOUNT = TRANSACTION_TYPE_JABBER_BASE + 7;

    /**
     * 批量获取资讯
     */
    public static final int TRANSACTION_TYPE_GETINFOIDS = TRANSACTION_TYPE_JABBER_BASE + 8;

    /**
     * 获取资讯列表
     */
    public static final int TRANSACTION_TYPE_GETINFOLIST = TRANSACTION_TYPE_JABBER_BASE + 9;

    /**
     * 获取资讯正文
     */
    public static final int TRANSACTION_TYPE_GETINFODETAIL = TRANSACTION_TYPE_JABBER_BASE + 10;
    /**
     * 获取资讯评论，转发，赞
     */
    public static final int TRANSACTION_TYPE_GETINFOCFP = TRANSACTION_TYPE_JABBER_BASE + 11;
    /**
     * 赞资讯
     */
    public static final int TRANSACTION_TYPE_PRAISEINFO = TRANSACTION_TYPE_JABBER_BASE + 12;
    /**
     * 反馈官方资讯
     */
    public static final int TRANSACTION_TYPE_FEEDBACK_1 = TRANSACTION_TYPE_JABBER_BASE + 13;
    /**
     * 举报用户讨论
     */
    public static final int TRANSACTION_TYPE_REPORT = TRANSACTION_TYPE_JABBER_BASE + 14;
    /**
     * 评论资讯
     */
    public static final int TRANSACTION_TYPE_COMMENTINFO = TRANSACTION_TYPE_JABBER_BASE + 15;
    /**
     * 转发资讯
     */
    public static final int TRANSACTION_TYPE_FORWARDINFO = TRANSACTION_TYPE_JABBER_BASE + 16;

    /**
     * 环回类型，用于内部传递数据
     */
    public static final int TRANSACTION_LOOPBACK = 1;

    /**
     * （订阅）获取游戏类、其他类主题列表
     */
    public static final int TRANSACTION_TYPE_GET_SUBJECT_LIST = 2;


    /**
     * 搜索主题和资讯源
     */
    public static final int TRANSACTION_TYPE_SEARCH_SUBJECT_AND_SOURCE = 3;

    /**
     * 获取最新资讯源列表
     */
    public static final int TRANSACTION_TYPE_GET_LATEST_SOURCE_LIST = 4;

    /**
     * 获取最热主题
     */
    public static final int TRANSACTION_TYPE_GET_HOTEST_SUBJECT_LIST = 5;

    /**
     * 获取推荐主题
     */
    public static final int TRANSACTION_TYPE_GET_RECOMMEND_SUBJECT_LIST = 6;

    /**
     * 获取主题详情
     */
    public static final int TRANSACTION_TYPE_GET_SUBJECT_DETAIL = 7;

    /**
     * 获取资讯源详情
     */
    public static final int TRANSACTION_TYPE_GET_SOURCE_DETAIL = 8;

    /**
     * 订阅
     */
    public static final int TRANSACTION_TYPE_SUBSCRIBE = 9;

    /**
     * 取消订阅
     */
    public static final int TRANSACTION_TYPE_UNSUBSCRIBE = 10;

    /**
     * 获取用户订阅的主题
     */
    public static final int TRANSACTION_TYPE_GET_SUBSCRIBE_LIST = 11;

    /**
     * 找朋友-人气榜
     */
    public static final int TRANSACTION_TYPE_GET_POP_FRIEND_LIST = 12;

    /**
     * 获取热门话题
     */
    public static final int TRANSACTION_TYPE_GET_TOPIC_LIST = 13;

    /**
     * 获取用户信息
     */
    public static final int TRANSACTION_TYPE_GET_USER_DETAIL = 14;

    /**
     * 获取用户关注列表
     */
    public static final int TRANSACTION_TYPE_GET_FOLLOW_LIST = 15;

    /**
     * 获取用户粉丝列表
     */
    public static final int TRANSACTION_TYPE_GET_FANS_LIST = 16;

    /**
     * 关注
     */
    public static final int TRANSACTION_TYPE_FOLLOW = 17;

    /**
     * 取消关注
     */
    public static final int TRANSACTION_TYPE_CANCEL_FOLLOW = 18;
    /**
     * 获取资讯源下资讯列表
     */
    public static final int TRANSACTION_TYPE_GET_SOURCE_INFO_LIST = 19;
    /**
     * 修改用户信息
     */
    public static final int TRANSACTION_TYPE_UPDATE_USER = 20;

    /**
     * 获取用户动态id
     */
    public static final int TRANSACTION_TYPE_GET_DYNAMIC_IDS = 21;

    /**
     * 获取用户动态信息
     */
    public static final int TRANSACTION_TYPE_GET_DYNAMIC_LIST = 22;
    /**
     * 获取通知列表
     */
    public static final int TRANSACTION_TYPE_GET_ADVICE_LIST = 23;
    /**
     * 获取猜你喜欢的用户
     */
    public static final int TRANSACTION_TYPE_GET_GUESS_FRIEND_LIST = 24;
    /**
     * 获取主题下讨论列表
     */
    public static final int TRANSACTION_TYPE_GET_SUBJECT_INFO_LIST = 25;
    /**
     * 发现讨论-最热
     */
    public static final int TRANSACTION_TYPE_GET_POP_DISCUSS_LIST = 26;
    /**
     * 发现讨论-猜你喜欢
     */
    public static final int TRANSACTION_TYPE_GET_GUESS_DISCUSS_LIST = 27;
    /**
     * 获取话题下讨论列表
     */
    public static final int TRANSACTION_TYPE_GET_TOPIC_INFO_LIST = 28;
    /**
     * 获取被评论的讨论列表
     */
    public static final int TRANSACTION_TYPE_GET_COMMENT_DISCUSS_LIST = 29;
    /**
     * 获取@我的讨论列表
     */
    public static final int TRANSACTION_TYPE_GET_AT_DISCUSS_LIST = 30;
    /**
     * 获取赞我的讨论列表
     */
    public static final int TRANSACTION_TYPE_GET_PRAISE_DISCUSS_LIST = 31;
    /**
     * 获取赞我的讨论列表
     */
    public static final int TRANSACTION_TYPE_GET_USER_DISCUSS_LIST = 32;

    protected class XoneNotifyTransaction extends NotifyTransaction {

        public XoneNotifyTransaction(AsyncTransaction tran, Object data,
                int type, int code) {
            super(tran, data, type, code);
        }

        public XoneNotifyTransaction(List<AsyncTransaction> trans, Object data,
                int type, int code) {
            super(trans, data, type, code);
        }

        @Override
        public void doBeforeTransact() {
            if (isSuccessNotify()) {
                Object data = getData();
                if (data != null) {
                    try {
                        do {
                            BaseData base = null;
                            if (data instanceof String) {
                                Gson gson = new Gson();
                                base = gson.fromJson((String)data, BaseData.class);
                            } else if (data instanceof HttpCache) {
                                String str = readString(null, ((HttpCache) data).LocalFile
                                        .openInputStream(), ((HttpCache) data).Charset);
                                Gson gson = new Gson();
                                base = gson.fromJson(str, BaseData.class);
                            } else {
                                setNotifyTypeAndCode(NOTIFY_TYPE_ERROR, 0);
                                break;
                            }
                            int code = base.resCode;
                            code = XoneServiceCode.protocolCodeToClientCode(code);
                            if(code == XoneServiceCode.PROTOCOL_CODE_SUCCESS){
                                resetData(base.data);
                            } else {
                                String error = base.resReason;
                                resetData(error);
                                if (code == XoneServiceCode.PROTOCOL_COOKIE_INVALID) {
                                    setNotifyTypeAndCode(NOTIFY_TYPE_ERROR, code, false);
                                } else {
                                    setNotifyTypeAndCode(NOTIFY_TYPE_ERROR, code);
                                }

                            }

                        } while (false);
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                        if (mRequest != null && mRequest instanceof THttpRequest) {
                            THttpRequest httpRequest = (THttpRequest) mRequest;
                            HttpCacheManager.deleteHttpCache(httpRequest);
                        }

                        setNotifyTypeAndCode(NOTIFY_TYPE_ERROR,
                                TransTypeCode.ERR_CODE_DATA_PARSE_EXCEPTION);
                    }
                } else {
                    setNotifyTypeAndCode(NOTIFY_TYPE_ERROR, 0);
                }
            }
        }

    }

    @Override
    public NotifyTransaction createNotifyTransaction(Object data,
            int notifyType, int code) {
        return new XoneNotifyTransaction(this, data, notifyType, code);
    }

    @Override
    public NotifyTransaction createNotifyTransaction(
            List<AsyncTransaction> trans, Object data, int notifyType, int code) {
        return new XoneNotifyTransaction(trans, data, notifyType, code);
    }

    @Override
    protected void sendRequest(Object obj, AsyncTransaction trans) {
        mRequest = obj;
        super.sendRequest(obj, trans);
    }

    @Override
    protected final void onTransactionSuccess(int code, Object obj) {
        onXoneTransactionSuccess(code, obj);
    }

    @Override
    protected final void onTransactionError(int errCode, Object obj) {
        if (errCode == XoneServiceCode.PROTOCOL_COOKIE_INVALID) {
            if(XoneService.getInstance().isLoging()){
                XoneService.getInstance().addToWattingList(this);
            } else {
                Account acc = ManagerAccount.getInstance().getCurrentAccount();
                XoneService.getInstance().setIsLoging(true);
                XoneService.getInstance().addToWattingList(this);
                if(acc == null){
                    acc = ManagerAccount.getInstance().getNewestAccount();
                }
                if(acc != null) {
                    XoneService.getInstance().doLogin(acc.mUserType, acc.mUserName, acc.mPassword);
                }else{
//                    onXoneTransactionError(errCode, obj);
                    XoneService.getInstance().doAnomyousLogin();
                }
            }
        } else if(errCode == XoneServiceCode.PROTOCOL_CODE_ENCRYPT_ERROR){
            XoneProtocol.getInstance().setIntitId(null);
            XoneProtocol.getInstance().setEncryptedKey(null);
            onXoneTransactionError(errCode, obj);
        }else {
            onXoneTransactionError(errCode, obj);
        }
    }

    protected void onXoneTransactionSuccess(int code, Object obj) {

    }

    protected void onXoneTransactionError(int errCode, Object obj) {
        notifyError(errCode, obj);
    }
}
